import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { ComponentGroup, PageData, ComponentInstance } from '@/types/visual-app'
import { useDynamicComponentStore } from '@/store/dynamicComponent'

export const useVisualStore = defineStore('dynamicVisual', () => {
  const dynamicComponentStore = useDynamicComponentStore()
  const pages = ref<PageData[]>([])
  const currentPage = ref<PageData>()
  const currentPageIndex = ref<number>(-1)
  const currentComponents = ref<ComponentInstance[]>([])
  const currentGroups = ref<ComponentGroup[]>([]) // 分组数据
  const debugMode = ref<boolean>(false)

  function setPages(data: PageData[]) {
    pages.value = data
    return currentPage.value
  }

  function getPage(index: number) {
    currentPage.value = pages.value?.[index]
    return currentPage.value
  }

  function getComponents(groupId: string) {
    const group = currentGroups.value.find(g => g.id === groupId)
    return group?.componentIds || []
  }

  function getGroup(groupId: string) {
    return currentGroups.value.find(g => g.id === groupId)
  }

 
 function addComponentToGroup(groupId: string, componentIds: string[]) {
   // 1. 查找目标分组
   const groupIndex = currentGroups.value.findIndex(g => g.id === groupId);
   if (groupIndex === -1) {
     console.warn(`未找到ID为 ${groupId} 的分组`);
     return undefined; // 分组不存在时提前返回
   }
 
   // 2. 更新分组的组件ID列表（自动去重）
   const targetGroup = currentGroups.value[groupIndex];
   const mergedComponentIds = [
     ...new Set([
       ...(targetGroup.componentIds || []), // 现有组件ID
       ...componentIds                     // 新增组件ID
     ])
   ];
 
   // 3. 更新关联组件的分组信息
   currentComponents.value
     .filter(comp => componentIds.includes(comp.id))
     .forEach(comp => {
       comp.groupId = groupId;
       comp.isGrouped = true;
     });
 
   // 4. 生成新的分组数组（不可变更新）
   const updatedGroups = [...currentGroups.value];
   updatedGroups[groupIndex] = {
     ...targetGroup,
     componentIds: mergedComponentIds
   };
 
   // 5. 更新响应式数据
   currentGroups.value = updatedGroups;
 
   return updatedGroups[groupIndex];
 }
 
/**
 * 从分组中移除指定组件（如果分组为空则自动移除）
 * @param componentId 要移除的组件ID
 * @param groupId 目标分组ID
 * @returns 更新后的分组信息 | undefined（分组不存在时）
 */
const removeComponentFromGroup = (componentId: string, groupId: string) => {
  // 1. 验证分组是否存在
  const groupIndex = currentGroups.value.findIndex(g => g.id === groupId);
  if (groupIndex === -1) {
    console.warn(`未找到ID为 ${groupId} 的分组`);
    return undefined;
  }

  // 2. 验证组件是否存在
  const componentIndex = currentComponents.value.findIndex(c => c.id === componentId);
  if (componentIndex === -1) {
    console.warn(`未找到ID为 ${componentId} 的组件`);
    return undefined;
  }

  // 3. 创建不可变更新数据
  let updatedGroups = [...currentGroups.value];
  const updatedComponents = [...currentComponents.value];

  // 4. 更新组件状态
  updatedComponents[componentIndex] = {
    ...updatedComponents[componentIndex],
    groupId: undefined,
    isGrouped: false
  };

  // 5. 更新分组组件列表
  const currentComponentIds = updatedGroups[groupIndex].componentIds || [];
  const newComponentIds = currentComponentIds.filter(id => id !== componentId);

  // 6. 检查并处理空分组
  if (newComponentIds.length === 0) {
    // 移除空分组
    updatedGroups = updatedGroups.filter((_, index) => index !== groupIndex);
  } else {
    // 更新非空分组
    updatedGroups[groupIndex] = {
      ...updatedGroups[groupIndex],
      componentIds: newComponentIds
    };
  }

  // 7. 提交更新
  currentGroups.value = updatedGroups;
  currentComponents.value = updatedComponents;

  // 8. 返回结果（如果分组被移除则返回undefined）
  return newComponentIds.length > 0 ? updatedGroups[groupIndex] : undefined;
};
 
  const triggerEventMethods = async (bindings: any[], eventType: string, ...args: any[]) => {
    if (!debugMode.value) return

    const eventBindings = bindings.filter(
      b => b.event === eventType && b.target && b.targetMethod
    )

    for (const binding of eventBindings) {
      if (binding.targetType === 'group') {
        playAnimation(binding.targetMethod, binding.target)
      } else {
        const instance = dynamicComponentStore.getRef(binding.target)
        if (!instance?.ref?.[binding.targetMethod]) continue

        if (binding.params?.length > 0) {
          const param = transformData(binding.params, args[0])
          instance.ref[binding.targetMethod](param)
        } else {
          instance.ref[binding.targetMethod](...args)
        }
      }
    }
  }

  function transformData(configs: any, data: any) {
    const result: any = {}
    configs.forEach((config: any) => {
      const { source, target, pSource, pTarget } = config

      // 获取源数据的值（支持多级 pSource）
      let sourceValue
      if (pSource) {
        const sourcePath = pSource.split(',')
        sourceValue = sourcePath.reduce((obj: any, key: any) => obj?.[key], data)
        sourceValue = sourceValue?.[source] // 最后取 source 字段
      } else {
        sourceValue = data[source]
      }

      if (sourceValue === undefined) return // 如果源数据不存在，跳过

      // 构造目标路径（支持多级 pTarget）
      const targetPath = pTarget ? pTarget.split(',') : []
      let currentTarget = result

      // 遍历并创建嵌套结构（除了最后一层）
      for (let i = 0; i < targetPath.length - 1; i++) {
        const key = targetPath[i]
        currentTarget[key] = currentTarget[key] || {}
        currentTarget = currentTarget[key]
      }

      // 设置目标值
      const finalKey = targetPath[targetPath.length - 1] || target
      currentTarget[finalKey] = sourceValue
    })
    return result
  }

  const ANIMATION_MAP = {
    fadeRight: {
      enter: 'animate__fadeInRightBig',
      leave: 'animate__fadeOutRightBig',
      events: {
        enter: 'fadeInRightAnimationend',
        leave: 'fadeOutRightAnimationend'
      }
    },
    fadeLeft: {
      enter: 'animate__fadeInLeftBig',
      leave: 'animate__fadeOutLeftBig',
      events: {
        enter: 'fadeInLeftAnimationend',
        leave: 'fadeOutLeftAnimationend'
      }
    }
  }

  const playAnimation = (targetMethod: string, target: string) => {
    const group = getGroup(target)
    if (!group) return

    const animationType = targetMethod.includes('Right') ? 'fadeRight' : 'fadeLeft'
    for (const componentId of group.componentIds || []) {
      const instance = dynamicComponentStore.getRef(componentId)
      if (!instance?.ref?.$el) continue

      // 设置动画属性
      if (!instance.props.enterAnimation) {
        instance.props.enterAnimation = ANIMATION_MAP[animationType].enter
        instance.props.leaveAnimation = ANIMATION_MAP[animationType].leave
      }

      // 切换可见状态
      instance.props.visible = !instance.props.visible

      // 触发相应事件
      const eventType = instance.props.visible ? 'enter' : 'leave'
      triggerEventMethods(
        group.bindings || [],
        ANIMATION_MAP[animationType].events[eventType],
        []
      )
    }
  }

  return {
    debugMode,
    pages,
    currentPageIndex,
    currentComponents,
    currentGroups,
    currentPage,
    getPage,
    setPages,
    getComponents,
    getGroup,
    addComponentToGroup,
	removeComponentFromGroup,
    transformData,
    playAnimation,
    triggerEventMethods
  }
})